using System;
using System.IO;
using System.Text.Json;

namespace DownloadTool
{
    public class AppSettings
    {
        private static readonly string SettingsFilePath = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory, "settings.json");
        
        private static AppSettings _instance;
        public static AppSettings Instance => _instance ??= Load();

        public string DefaultDownloadPath { get; set; }

        public AppSettings()
        {
            // Default to "Download" folder in the current directory
            DefaultDownloadPath = Path.Combine(
                Directory.GetCurrentDirectory(), "Download");
        }

        public static AppSettings Load()
        {
            try
            {
                if (File.Exists(SettingsFilePath))
                {
                    string json = File.ReadAllText(SettingsFilePath);
                    var settings = JsonSerializer.Deserialize<AppSettings>(json);
                    if (settings != null)
                    {
                        return settings;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error loading settings: {ex.Message}");
            }

            // If file doesn't exist or there was an error, create default settings
            var defaultSettings = new AppSettings();
            
            // Ensure the default download directory exists
            EnsureDirectoryExists(defaultSettings.DefaultDownloadPath);
            
            return defaultSettings;
        }

        public void Save()
        {
            try
            {
                string json = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(SettingsFilePath, json);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error saving settings: {ex.Message}");
            }
        }

        public static void EnsureDirectoryExists(string path)
        {
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Error creating directory: {ex.Message}");
                }
            }
        }
    }
}